#include "Socket.hpp"
#include "log.hpp"
#include <poll.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <vector>

static const int FD_SET_SIZE = 1024;

class Poll
{
public:
    Poll(uint16_t port) : _port(port)  
    {
        for (int i = 0; i < FD_SET_SIZE; i++)
        {
            _event_fds[i].fd = -1;
            _event_fds[i].events = 0;
            _event_fds[i].revents = 0;
        }
    }
  

    void Init()
    {
        _sock.Socket();
        _sock.Bind(_port);
        _sock.Listen();

        _event_fds[0].fd = _sock.GetListenSock();
        _event_fds[0].events = POLLIN;
        _event_fds[0].revents = 0;
    }

    void Start()
    {
        for (;;)
        {
            int n = poll(_event_fds, FD_SET_SIZE, -1);
            switch (n)
            {
            case -1:
                lg(Error, "select error: code:%d msg:%s", errno, strerror(errno));
                exit(-1);
                break;
            case 0:
                std::cout << "超时，进行下一次等待" << std::endl;
                break;
            default:
                std::cout << "有" << n << "个文件描述符处于就绪状态" << std::endl;
                Dispatcher();
                break;
            }
        }
    }

    void Accepter() // 链接管理器
    {
        std::string clientip;
        uint16_t clientport;
        int sock = _sock.Accept(clientip, clientport);
        if (sock < 0) return;
            lg(Info, "accept success, %s: %d, sock fd: %d", clientip.c_str(), clientport, sock);

        int pos = 1;
        for (; pos < FD_SET_SIZE; ++pos)
        {
            if (_event_fds[pos].fd != -1)
                continue;

            _event_fds[pos].fd = sock;
            _event_fds[pos].events = POLLIN;
            _event_fds[pos].revents = 0;
            break;
        }
        // 满了  选择退出或者扩容
        if (pos == FD_SET_SIZE)
        {
            lg(Warning, "_fd_array full");
            close(sock);
        }
    }

    void Recver(int fd, int pos)
    {
        char buffer[128];
        std::string res = "get mseeage, fd: ";
        res += std::to_string(fd);
        res += " msg: ";
        
        int n = recv(fd, buffer, sizeof(buffer) - 1, 0);

        if (n < 0)
        {
            lg(Error, "recv error, fd:%d, code:%d, msg:%s", fd, errno, strerror(errno));
            _event_fds[pos].fd = -1;
            close(fd);
            return;
        }
        else if (0 == n)
        {
            // 对方写端关闭,也有可能是刚好读完
            lg(Debug, "close file, fd:%d", fd);
            _event_fds[pos].fd = -1;
            close(fd);
            return;
        }
        else
        {
            buffer[n] = 0;
            res += buffer;
        }
        
        std::cout << res << std::endl;
    }

    // 负责调度
    void Dispatcher()
    {
        for (int i = 0; i < FD_SET_SIZE; ++i)
        {
            if (_event_fds[i].fd == -1)
                continue;

            if (_event_fds[i].revents != 0)
            {
                if (_event_fds[i].fd == _sock.GetListenSock())
                    Accepter();
                else
                    Recver(_event_fds[i].fd, i);
            }
        }
    }
    ~Poll()
    {
        _sock.Close();
    }

private:
    Sock _sock;
    struct pollfd _event_fds[FD_SET_SIZE];
    uint16_t _port;
};
